package cn.tedu._06article.controller;


import cn.tedu._06article.base.response.JsonResult;
import cn.tedu._06article.base.response.StatusCode;
import cn.tedu._06article.mapper.UserMapper;
import cn.tedu._06article.pojo.dto.UserArticleParam;
import cn.tedu._06article.pojo.dto.UserLoginParam;
import cn.tedu._06article.pojo.entity.Article;
import cn.tedu._06article.pojo.vo.ArticleVO;
import cn.tedu._06article.pojo.vo.UserVO;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/v1/user")
@Tag(name = "01-用户管理接口")
@Slf4j
@Validated
public class UserController {
    @Autowired
    private UserMapper userMapper;

    @PostMapping("login")
    @Operation(summary = "用户登录")
    @ApiOperationSupport(order = 10)
    public JsonResult login(@RequestBody @Validated UserLoginParam userLoginParam, HttpSession session) {
        log.debug("开始处理用户登录"+userLoginParam);
        UserVO userVO = userMapper.selectByUsernameAndPassword(userLoginParam);
        if(userVO==null){
            return new JsonResult(StatusCode.USERNAME_PASSWORD_ERROR);
        }
        session.setAttribute("user",userVO);

        return JsonResult.ok();
    }

    @PostMapping("article")
    @Operation(summary = "发布文章")
    @ApiOperationSupport(order = 20)
    public JsonResult addArticle(@RequestBody @Validated UserArticleParam userArticleParam, HttpSession session) {
        log.debug("开始处理发布文章");
        UserVO userVO = (UserVO) session.getAttribute("user");
        int count = userMapper.addArticle(userArticleParam, userVO.getId());
        if(count!=1){
            return new JsonResult(StatusCode.OPERATION_FAILED);
        }
        return JsonResult.ok();
    }

    @GetMapping("selectByArticle")
    @Operation(summary = "查询文章")
    @ApiOperationSupport(order = 30)
    public JsonResult selectByArticle(@Range(min=1L,max=100L,message = "文章id范围1-100之间") Long id){
        log.debug("开始处理查询文章");
        ArticleVO articleVO = userMapper.selectByArticle(id);
        return JsonResult.ok(articleVO);
    }
}
